<?php
declare (strict_types=1);

namespace app\course\model\base\admin;

use app\common\logic\Attach;
use app\common\model\BaseModel;
use app\course\logic\base\CourseCert;
use app\course\model\base\CourseSection;
use app\school\model\school\admin\School;
use app\user\model\teacher\Teacher;
use app\user\model\user\Account;

/**
 * 定义课程数据模型
 */
class Course extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'course';
    protected $json = ['ext_data'];
    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    public function coverUrl()
    {
        return $this->belongsTo(Attach::class, 'cover', 'id')->bind(['cover_url' => 'fileurl']);
    }

    /**
     *  获取状态显示文字
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-14
     *
     * @param string $value
     * @param        $data
     * @return string
     */
    protected function getCourseTypeTextAttr($value = '', $data): string
    {
        $text = [
            1 => '点播',
            2 => '直播',
            3 => '面授',
            4 => '班级',
            5 => '点播课时',
        ];

        return $text[$data['course_type']];
    }

    /**
     * 获取课程的产品信息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-26
     *
     * @return   [type]                         [description]
     */
    public static function getCourseResourceType($course)
    {
        $type = [
            1 => 'video',
            2 => 'live',
            3 => 'offline',
            4 => 'classes',
        ];

        if ($course['course_type'] == 2 && $course['course_live_type'] == 2) {
            $resource_type = 'live_small';
        } else {
            $resource_type = $type[$course['course_type']] ?? 'public';
        }

        return $resource_type;
    }

    // 关联机构名称
    public function school()
    {
        return $this->belongsTo(School::class, 'mhm_id')->bind(['school_name' => 'title'])->removeOption('soft_delete');
    }

    public function teacher()
    {
        return $this->hasOneThrough(Account::class, Teacher::class, 'id', 'id', 'teacher_id', 'user_id');
    }

    /**
     * 简介格式转换,防止富文本编辑器中有表情等
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-21
     *
     * @param string $value [description]
     */
    public function setInfoAttr($value = '')
    {
        return base64_encode($value);
    }

    /**
     * 简介格式转换,防止富文本编辑器中有表情等
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-21
     *
     * @param string $value [description]
     * @return   [type]                                [description]
     */
    public function getInfoAttr($value = '')
    {
        if (!$value) {
            return '';
        }
        if ($value === base64_encode((string)base64_decode($value, true))) {
            return base64_decode($value);
        } else {
            return $value;
        }
    }

    /**
     * 成功创建之后
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-14
     */
    public static function onAfterInsert($course)
    {
        if ($course->is_recommend) {
            self::cleanCache($course);
        }
    }

    /**
     * 成功修改之后
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-14
     */
    public static function onAfterUpdate($course)
    {
        if ($course->recommend_change) {
            self::cleanCache($course);
        }

        if ($course->update_status === 0) {
            // 检查是否发放证书
            app(CourseCert::class)->addCert($course->id);
        }
    }

    /**
     * 成功删除之后
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-14
     */
    public static function onAfterDelete($course)
    {
        if ($course->is_recommend) {
            self::cleanCache($course);
        }
    }

    /**
     * 清除缓存
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-14
     */
    public static function cleanCache($course)
    {
        // 清理推荐课程缓存
        cache('recommend_course_' . $course->mhm_id, null);

        // 清理推荐分类课程缓存
        $category = explode(',', trim($course->category, ','));

        foreach ($category as $cate) {
            if (cache("category_course_" . $cate)) {
                cache("category_course_" . $cate, null);

                if (file_exists('home_pc.txt')) unlink('home_pc.txt');
                if (file_exists('home_ot.txt')) unlink('home_ot.txt');
            }
        }
    }

    // 关联课时章节
    public function sec()
    {
        return $this->hasOne(CourseSection::class, 'course_id');
    }

    public function teacherName()
    {
        return $this->belongsTo(Teacher::class, 'teacher_id')->with(['teacher_name'])->bind(['teacher_name' => 'title']);
    }
}
